<template>
  <div class="code-editor-container" :style="containerStyle">
    <div class="editor-container" :style="editorStyle">
      <!-- 顶部固定区域 -->
      <div class="fixed-header" v-if="firstLine.length>0">
        <div class="line-numbers-header">
          <!-- 顶部固定行不显示行号 -->
        </div>
        <div class="code-line fixed-line">{{ firstLine }}</div>
      </div>

      <!-- 中间可滚动区域 -->
      <div class="scrollable-area">
        <div class="line-numbers" ref="lineNumbers">
          <div v-for="(line, index) in editableLines" :key="index" class="line-number">
            {{ index + 1 }}
          </div>
        </div>
        <div class="code-editor" ref="codeEditor">
          <textarea
            class="editable-area"
            :value="editableCode"
            @input="handleInput"
            @scroll="syncScroll"
            ref="editableCode"
            :placeholder="placeholder"
          ></textarea>
        </div>
      </div>

      <!-- 底部固定区域 -->
      <div class="fixed-footer" v-if="lastLine.length>0">
        <div class="line-numbers-footer">
          <!-- 底部固定行不显示行号 -->
        </div>
        <div class="code-line fixed-line">{{ lastLine }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CodeEditor',
  props: {
    // 初始代码内容（不包含固定行）
    value: {
      type: String,
      default: ''
    },
    // 第一行固定内容
    firstLine: {
      type: String,
      default: ''
    },
    // 最后一行固定内容
    lastLine: {
      type: String,
      default: ''
    },
    // 占位符文本
    placeholder: {
      type: String,
      default: '// 在这里编写你的代码'
    },
    // 是否显示复制按钮
    showCopyButton: {
      type: Boolean,
      default: true
    },
    // 编辑器高度
    height: {
      type: [String, Number],
      default: 200
    },
    // 编辑器最小高度
    minHeight: {
      type: [String, Number],
      default: null
    },
    // 编辑器最大高度
    maxHeight: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      editableCode: this.value,
      copyButtonText: '复制代码'
    }
  },
  computed: {
    editableLines() {
      return this.editableCode.split('\n');
    },
    totalLines() {
      const baseLines = this.editableLines.length;
      return baseLines + (this.firstLine ? 1 : 0) + (this.lastLine ? 1 : 0);
    },
    charCount() {
      return this.editableCode.length;
    },
    // 获取完整代码（包含固定行）
    fullCode() {
      let code = '';
      if (this.firstLine) {
        code += this.firstLine + '\n';
      }
      code += this.editableCode;
      if (this.lastLine) {
        if (this.editableCode) code += '\n';
        code += this.lastLine;
      }
      return code;
    },
    // 容器样式
    containerStyle() {
      const style = {};
      if (this.minHeight) {
        style.minHeight = typeof this.minHeight === 'number' ? `${this.minHeight}px` : this.minHeight;
      }
      if (this.maxHeight) {
        style.maxHeight = typeof this.maxHeight === 'number' ? `${this.maxHeight}px` : this.maxHeight;
      }
      return style;
    },
    // 编辑器样式
    editorStyle() {
      return {
        height: typeof this.height === 'number' ? `${this.height}px` : this.height
      };
    }
  },
  watch: {
    // 监听外部传入的value变化
    value(newVal) {
      if (newVal !== this.editableCode) {
        this.editableCode = newVal;
        this.$nextTick(this.updateLineNumbers);
      }
    },
    // 监听内部代码变化，触发input事件
    editableCode(newVal) {
      this.$emit('input', newVal);
      this.$emit('change', this.fullCode);
    },
    // 监听高度变化
    height() {
      this.$nextTick(this.updateLineNumbers);
    }
  },
  methods: {
    handleInput(event) {
      this.editableCode = event.target.value;
      this.updateLineNumbers();
    },
    updateLineNumbers() {
      this.$nextTick(() => {
        const textarea = this.$refs.editableCode;
        if (textarea) {
          // 自动调整高度
          textarea.style.height = 'auto';
          const newHeight = Math.max(textarea.scrollHeight, parseInt(this.height) || 200);
          textarea.style.height = newHeight + 'px';

          // 更新行号显示
          this.updateLineNumbersDisplay();
        }
      });
    },
    updateLineNumbersDisplay() {
      const lineNumbers = this.$refs.lineNumbers;
      if (lineNumbers) {
        let numbersHTML = '';
        for (let i = 0; i < this.editableLines.length; i++) {
          numbersHTML += `<div class="line-number">${i + 1}</div>`;
        }
        lineNumbers.innerHTML = numbersHTML;
      }
    },
    syncScroll() {
      const textarea = this.$refs.editableCode;
      const lineNumbers = this.$refs.lineNumbers;
      if (textarea && lineNumbers) {
        lineNumbers.scrollTop = textarea.scrollTop;
      }
    },
    copyCode() {
      navigator.clipboard.writeText(this.fullCode).then(() => {
        this.copyButtonText = '已复制!';
        setTimeout(() => {
          this.copyButtonText = '复制代码';
        }, 2000);
      });
      this.$emit('copy', this.fullCode);
    },
    // 公共方法：获取完整代码
    getFullCode() {
      return this.fullCode;
    },
    // 公共方法：设置代码
    setCode(code) {
      this.editableCode = code;
      this.updateLineNumbers();
    },
    // 公共方法：清空代码
    clearCode() {
      this.editableCode = '';
      this.updateLineNumbers();
    }
  },
  mounted() {
    this.updateLineNumbers();
  }
}
</script>

<style scoped>
.code-editor-container {
  width: 100%;
  background: #000000;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  border: 1px solid #333;
  border-radius: 2px;
}

.editor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 固定区域通用样式 */
.fixed-header,
.fixed-footer {
  display: flex;
  align-items: stretch;
  min-height: 21px;
  line-height: 21px;
}

.fixed-header {
  background: #000000;
  border-bottom: 1px solid #333;
}

.fixed-footer {
  background: #000000;
  border-top: 1px solid #333;
}

/* 行号容器 */
.line-numbers-header,
.line-numbers-footer {
  min-width: 50px;
  background: #000000;
  border-right: 1px solid #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 可滚动区域 */
.scrollable-area {
  display: flex;
  flex: 1;
  overflow: auto;
  background: #000000;
}

/* 行号区域 */
.line-numbers {
  background: #000000;
  color: #ffffff;
  padding: 0;
  text-align: center;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 12px;
  line-height: 21px;
  user-select: none;
  border-right: 1px solid #333;
  min-width: 50px;
  flex-shrink: 0;
}

.line-number {
  padding: 0 8px;
  min-height: 21px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: #ffffff;
}

/* 代码编辑区域 */
.code-editor {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.code-line {
  flex: 1;
  padding: 0 15px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 12px;
  line-height: 21px;
  color: #d4d4d4;
  min-height: 21px;
  display: flex;
  align-items: center;
  background: #000000;
}

.fixed-line {
  background: #000000;
  color: #ffffff;
  font-weight: bold;
}

/* 可编辑区域 */
.editable-area {
  width: 100%;
  height: 100%;
  background: #000000;
  color: #d4d4d4;
  border: none;
  outline: none;
  resize: none;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 12px;
  line-height: 21px;
  padding: 0 15px;
  margin: 0;
  box-sizing: border-box;
}

.editable-area::placeholder {
  color: #666666;
}

.editable-area::selection {
  background: #264f78;
  color: #ffffff;
}

/* 自定义滚动条样式 */
.scrollable-area::-webkit-scrollbar {
  width: 12px;
  height: 12px;
}

.scrollable-area::-webkit-scrollbar-track {
  background: #000000;
}

.scrollable-area::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 2px;
  border: 2px solid #000000;
}

.scrollable-area::-webkit-scrollbar-thumb:hover {
  background: #444444;
}

.scrollable-area::-webkit-scrollbar-corner {
  background: #000000;
}

/* 确保所有行的高度一致 */
.line-numbers .line-number,
.code-line,
.editable-area {
  min-height: 21px;
  line-height: 21px;
}
</style>
